<template>
	<view>
		<my-navbar :title="receiveUser"
				   :showBack="true"
				   :showLeft="false"
				   :bgColor="'#E54F91FF'"
				   :textColor="'#fff'"
		></my-navbar>
		
		<div class="Scroll">
			<view v-for="(item, index) in msgList" :key="index" :id="`item-${index}`">
				<view v-if="item.sendOutUserId === myId" class="send-item">
					<view class="msg">{{ item.msg }}</view>
					<image :src="myAvatar"></image>
				</view>
				<view v-else class="receive-item">
					<image :src="theirAvatar"></image>
					<view class="msg">{{ item.msg }}</view>
				</view>
			</view>
		</div>
		
		<view class="send">
			<textarea type="text" placeholder="请输入消息" v-model="msg"/>
			<button @click="send">发送</button>
		</view>
	</view>
</template>
<script setup>
import {ref, inject, watch, nextTick, reactive} from 'vue'
import {onLoad, onUnload, onShow} from '@dcloudio/uni-app';
import request from "@/utils/request";
import myNavbar from "@/components/my-navbar/my-navbar.vue";

const $store = inject('$store')
let msg = ref('')
// let item = ref('')
let sendOutUser = ref('')
let receiveUser = ref('')
let uid = ref('')
let myId = ref('')
let myAvatar = ref('')
let theirAvatar = ref('')
let msgList = ref([]) //消息记录
let websocket = reactive(null)


// watch(msgList.value, (newVal, oldVal) => {// scroll-view 滚动到底部
// 	nextTick(()=>{
// 		item.value = "item-" + (newval.length - 1)
// 		console.log('scroll', item.value)
// 	})
// },{
// 	deep: true,
// 	immediate: true
// })

onShow(() => {
	myAvatar.value = uni.getStorageSync('myAvatar') // 我的头像
	theirAvatar.value = uni.getStorageSync('theirAvatar') // 对方的头像
	myId.value = uni.getStorageSync('uid') // 我的id
	console.log('myId', myId.value)
	setTimeout(() => {
		window.scrollTo(0, document.body.scrollHeight)
		console.log('scroll', document.body.scrollHeight)
	}, 500)
})

onLoad((e) => {
	
	
	console.log('e', e)
	receiveUser.value = e.receiveUser // 对方的名字
	//触发vuex中的initSocket方法
	let myId = uni.getStorageSync('uid')
	uid.value = e.uid // 对方的id
	if ($store.state.socket == null) { // 避免多次创建socket
		$store.dispatch('initSocket')
	}
	
	//拿到vuex中的socket对象
	websocket = $store.state.socket
	
	uni.onSocketMessage(function (res) {
		console.log('详情页--收到服务器内容：' + res.data);
		let temp = res.data;
		if (temp.includes('聊天室人数为')) {
			return;
		}
		// 截取：之前的内容
		temp = temp.substring(temp.indexOf('：') + 1) // 截取消息内容
		console.log('temp', temp)
		let msgItem = {
			sendOutUserId: Number(uid.value),
			receiveUserId: myId,
			msg: temp,
		}
		msgList.value.push(msgItem)
		console.log('收到消息', msgItem, msgList.value);
		setTimeout(() => {
			window.scrollTo(0, document.body.scrollHeight)
		}, 300)
	});
	
	getMsg()
	
	//给回车键绑定发送事件且禁用换行
	document.onkeydown = function (e) {
		if (e.keyCode === 13) {
			send()
			return false
		}
	}
});

// 获取聊天记录
function getMsg() {
	let myId = uni.getStorageSync('uid')
	console.log('myId', myId)
	console.log('uid', uid.value)
	request.post('messageRecord/getMessage', {
		sendUserId: myId,
		receiveUserId: Number(uid.value),
	}).then(res => {
		console.log('获取消息', res)
		msgList.value = res.result
		uni.setStorageSync('msgCount', res.result.length) // 未读消息数
	})
}

function showMore() {
	console.log('触顶')
}


onUnload(() => {
	document.onkeydown = null
})


//发送消息
function send() {
	
	if (msg.value.trim() === '') {
		uni.showToast({
			title: '不允许发送空消息',
			icon: 'none',
		})
		return
	}
	request.post('socket/send/messageToUsername', {
		sendOutId: myId.value,
		receiveId: Number(uid.value),
		msg: msg.value,
		type: 0, // 0-私聊 1-群聊
	}).then(res => {
		if (res.msg === 'success') {
			let msgItem = {
				sendOutUserId: myId,
				receiveUserId: Number(uid.value),
				msg: msg.value,
			}
			msgList.value.push(msgItem)
			msg.value = '';
		}
	}).finally(() => {
		setTimeout(() => {
			window.scrollTo(0, document.body.scrollHeight)
		}, 300)
	})
}
</script>
<style scoped lang="scss">
.title {
	text-align: center;
	font-size: 28rpx;
	padding: 20rpx;
	background-color: #2f85fc;
	color: #fff;
}

.Scroll {
	padding: 120rpx 20rpx;
	//overflow: scroll;
	//max-height: calc(100vh - 300rpx);
	//margin-bottom: 140rpx;
	//box-sizing: border-box;
	
	.send-item, .receive-item {
		margin: 20rpx 0;
		
		image {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
		}
		
		.msg {
			font-size: 30rpx;
		}
	}
	
	.send-item {
		display: flex;
		justify-content: end;
		align-items: baseline;
		
		.msg {
			//超出换行
			max-width: 80%;
			padding: 10rpx;
			margin-right: 16rpx;
			border-radius: 10rpx;
			color: #fff;
			border: 1px solid #f0f0f0;
			word-wrap: break-word;
			text-align: justify;
			background-color: #2f85fc;
			position: relative;
			
			&::before {
				content: '';
				position: absolute;
				width: 0;
				height: 0;
				border-top: 14rpx solid transparent;
				border-bottom: 14rpx solid transparent;
				border-left: 14rpx solid #2f85fc;
				right: -10rpx;
				top: 0;
				transform: translateY(10%);
			}
		}
	}
	
	.receive-item {
		display: flex;
		justify-content: flex-start;
		align-items: baseline;
		
		.msg {
			max-width: 80%;
			padding: 10rpx;
			margin-left: 16rpx;
			box-sizing: border-box;
			border-radius: 10rpx;
			background-color: #E54F91FF;
			color: #fff;
			word-wrap: break-word;
			position: relative;
			
			&::before {
				content: '';
				position: absolute;
				width: 0;
				height: 0;
				border-top: 14rpx solid transparent;
				border-bottom: 14rpx solid transparent;
				border-right: 14rpx solid #E54F91FF;
				left: -10rpx;
				top: 0;
				transform: translateY(10%);
			}
		}
	}
}

.send {
	position: fixed;
	bottom: 0;
	width: 100%;
	display: flex;
	height: 120rpx;
	align-items: center;
	padding: 0 20rpx;
	background-color: #fff;
	
	textarea {
		flex: 1;
		height: 60rpx;
		border: 1px solid #f0f0f0;
		border-radius: 10rpx;
		padding: 0 20rpx;
	}
	
	button {
		width: 120rpx;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #007aff;
		color: #fff;
		border-radius: 10rpx;
		margin-left: 20rpx;
	}
}
</style>
